package com.jt.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jt.mapper.OrderItemMapper;
import com.jt.mapper.OrderMapper;
import com.jt.mapper.OrderShippingMapper;
import com.jt.pojo.Order;
import com.jt.pojo.OrderItem;
import com.jt.pojo.OrderShipping;
import com.jt.service.DubboOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author 张琪
 * @date 2020/12/17
 * @describe
 */
@Service(timeout = 3000)
public class OrderServiceImpl implements DubboOrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private OrderShippingMapper orderShippingMapper;

    @Override
    @Transactional
    public String saveOrder(Order order) {
//        因为订单号增长太快, 因此需要手动拼接主键id
        String orderId = "" + order.getUserId() + System.currentTimeMillis();

//        1. 完成订单入库的操作
        order.setOrderId(orderId);
        orderMapper.insert(order);

//        2. 入库订单物流信息
        OrderShipping orderShipping = order.getOrderShipping();
        orderShipping.setOrderId(orderId);
        orderShippingMapper.insert(orderShipping);

//        3. 完成订单商品入库信息
        List<OrderItem> orderItems = order.getOrderItems();
        for (OrderItem orderItem : orderItems) {
            orderItem.setOrderId(orderId);
            orderItemMapper.insert(orderItem);
        }

        System.out.println("订单入库完成!!");

        return orderId;

/*          手动写入时需要考虑更多的操作, 下面的方法记录的数据不够完成
//        向orderItem表中插入数据
        for (OrderItem item : order.getOrderItems()) {
            orderItemMapper.insert(item);
        }
//        向orderShipping表中插入数据
        orderShippingMapper.insert(order.getOrderShipping());
        orderMapper.insert(order);
        return order.getOrderId();*/
    }


    @Override
    public Order findOrderById(String orderId) {

        Order order = orderMapper.selectById(orderId);

        OrderShipping orderShipping = orderShippingMapper.selectById(orderId);
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", orderId);
        List<OrderItem> list = orderItemMapper.selectList(queryWrapper);
        order.setOrderItems(list).setOrderShipping(orderShipping);
        return order;
    }
}
